#include "head_c.h"

int cd(user_t* status, const portocol_t* portocol, int socket_fd){
    
    
    printf("--cd--\n");

    //准备接收服务端发来的回复:"failed" , '.', '..' , '\0' , 'dir_name'
    int  len = 0;
    int res = recv(socket_fd, &len, sizeof(int), 0);
    ERROR_CHECK(res, -1, "recv");

    printf("The len: %d\n", len);

    char buf[128] = {0};
    res = recv(socket_fd, buf, len, 0);
    ERROR_CHECK(res, -1, "recv");
    printf("The buf: %s\n", buf);


    //未找到目标文件夹
    if(strcmp(buf, "failed") == 0) {
        
        printf("没有找到这个目录。\n");
    

        //回到家目录命令
    }else if(strcmp(buf, "NULL") == 0){   
        
        memset(status->path, 0, sizeof(status->path));
        status->path[0] = '/';
        status->path[1] = '\0';


        //移动动至当前文件夹
    }else if(strcmp(buf, ".") == 0) {
        
        printf("The path: %s\n", status->path);
        return 0;

        //移动至父目录
    }else if(strcmp(buf, "..") == 0){

        //找到当前路径下的父目录:找到以’/‘分割的最后一个单词
        //若父目录为“用户家目录”
        if(strcmp(status->path, "/") == 0){
            int size = strlen(status->path);
            printf("The .. path: %s\n", status->path);
            printf("The .. len: %d\n", size);
            return 0;
        }
        
        int num = 0;
        int last_token;
        int n = strlen(status->path);
        for(int i = 0; i < n; i++) {
            if(status->path[i] == '/') {
                last_token = i;
                num++;
            }
        }

         status->path[last_token] = '\0';
         if(status->path[0] != '/'){
             status->path[0] = '/';
            status->path[1] = '\0';
         }
         //找到目标目录项
    }else{
        
        int len = strlen(status->path);
        if(status->path[len-1] != '/') {
            status->path[len] = '/';
            status->path[len+1] = '\0';
        }

        printf("cd:buf   %s \n", buf);
        //将服务端返回的参数名拼接至用户名之后的路径后面
        strcat(status->path, buf);

        //status->path[len] = '\0';dd
        //status->path[len+1] = '\0';
    }

    printf("The path: %s\n", status->path);
    return 0;
}

